<script setup>
import  { tool }  from "../../tool/index"
import { Search, Tools, List } from '@element-plus/icons-vue'
import axios from "axios"
import { ref, reactive, onMounted, computed, watch } from "vue"
import { Plus } from '@element-plus/icons-vue'
import md5 from 'js-md5'
// Axios 请求地址
const path = tool.serverPath+"api/app_api/user/"
const imagePath = tool.serverPath+"api/app_api/image/upload/"
// 获取文件选择对象，进行Ref绑定
const fileInputRef = ref(null)
// 初始化数据
var data = reactive({})
// 搜索范围选择器
var SelectValue = ref("ID")
// 性别选择器
var gender = {
    sex: ["male", "female", "other"],
    tips: ["男", "女", "未设置"]
}
// 搜索框
var input_txt = ref("")
// 判断 搜索框 是否进行隐藏
var disabledSearch = computed(() => {
    if (SelectValue.value == "gender") {
        input_txt.value = "male"
        return true
    }
    else {
        return false
    }
})
// 监听 查询选择器是否选择了 gender
watch(SelectValue, (newValue, oldValue) => {
    if (oldValue == "gender") {
        input_txt.value = ""
    }
})
// 选择器 的 option 选项
var userSelect = {
    user: ["id", "username", "email", "nickname", "gender"],
    tips: ["ID", "账号", "邮箱", "昵称", "性别"]
}
// 需要展示的数列
var prop = {
    fields: ["id", "username", "email", "nickname", "gender", "bio", "created_at", "updated_at"],
    tips: ["ID", "账号", "邮箱", "昵称", "性别", "简介", "注册时间", "更新时间"]
}
// 是否进行模糊查询
var bool = ref(false)
// 分页数据
let limit = ref(5)
let offset = ref(1)
let pageCount = ref(0)
// Axios 查询函数 
async function SearchUser() {
    try {
        const response = await axios.get(path + "get", {
            params: {
                key: "Search",
                limit: limit.value,
                offset: offset.value,
                data: {
                    OpLike: bool.value,
                    key: [SelectValue.value],
                    value: [input_txt.value]
                }
            }
        })
        data.data = response.data.data
        pageCount.value = response.data.count
    } catch (error) {
        alert(err)
    }
}
// 分页回调函数
function handlePageChange(value) {
    offset.value = value
    SearchUser()
}
// 添加数据弹出框
var dialogVisible = ref(false)
// 数据暂存对象
const User = {
    username: undefined,
    password: undefined,
    agePassword: undefined,
    email: undefined,
    nickname: "未命名",
    gender: "other",
    avatar: "暂无",
    bio: "暂无",
    created_at: new Date(),
    updated_at: new Date()
}
const addUser = ref(copyObj(User)) 
// 复制对象
function copyObj(value){
    const key = Object.keys(value)
    var temp = {}
    for (let index = 0; index < key.length; index++) {
        temp[`${key[index]}`] = value[key[index]]
    }
    return temp
}
// 打开添加窗口
function openData() {
    dialogVisible.value = true
}
// 操作提示
var tip = [{
    title: "数据不能为空",
    type: "info",
    description: "请检查数据"
}, {
    title: "两次密码不正确",
    type: "error",
    description: "请检查密码"
}, {
    title: "数据添加成功",
    type: "success",
    description: "操作成功"
}, {
    title: "账号已存在",
    type: "info",
    description: "请重新注册新的账号"
},]
var tips = ref()
// 添加数据 
async function addData() {
    for (let index = 0; index < Object.keys(addUser.value).length; index++) {
        if (Object.values(addUser.value)[index] == undefined) {
            tips.value = [tip[0]]
            return false
        }
    }
    try {
        const response = await axios.get(path + "get", {
            params: {
                key: "Search",
                columns: ["username"],
                data: {
                    key: ["username"],
                    value: [addUser.value.username]
                }
            }
        })
        if (response.data.count != 0) {
            tips.value = [tip[3]]
            return false
        }
    } catch (error) {
        alert(error+"sss")
    }
    if (addUser.value.agePassword == addUser.value.password) {
        uploadImage()
        await axios.post(path + "post", {
            key: "add",
            data: {
                key: Object.keys(addUser.value),
                value: Object.values(addUser.value)
            }
        }).then(date => {
            tips.value = [tip[2]]
        })
        return true
    } else {
        tips.value = [tip[1]]
        return false
    }
}
// 头像显示
const imageUrl = ref('')
const selectedImage = ref()
// 触发文件选择事件
function openFileInput() {
    fileInputRef.value.click()
}
// 封面对象转存
function handleFileChange(event) {
    // 获取文件对象进行存储
    const file = event.target.files[0]
    // 检查文件类型
    const allowedTypes = ['image/jpeg', 'image/png', 'image/gif']
    if (!allowedTypes.includes(file.type)) {
        alert('只允许上传JPEG、PNG或GIF格式的图片')
        return
    }
    // 检查文件大小（以字节为单位）
    const maxSizeInBytes = 5 * 1024 * 1024 // 5MB
    if (file.size > maxSizeInBytes) {
        alert('图片大小超过限制（最大为5MB）')
        return
    }
    // 将文件对象转存
    selectedImage.value = file
    // 将文件对象转换为URL
    imageUrl.value = URL.createObjectURL(file)
}
// 图片上传到服务器
async function uploadImage() {
    const formData = new FormData()
    if(selectedImage.value == null)
    return
    const file = selectedImage.value
    const fileExtension = file.name.split('.').pop()
    const fileName = md5(new Date().toString()) + '.' + fileExtension
    //   存储头像名称
    addUser.value.avatar = fileName
    if(showDialogConetent.value == true) {
        changeIndex.avatar = fileName
    }
    formData.append('file', file, fileName)
    try {
        await axios.post(imagePath, formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    })
    } catch (error) {
        
    }

}
// 关闭添加窗口
function clearData() {
    addUser.value = copyObj(User)
    dialogVisible.value = false
}
let showDialog = ref(false)
let deleIndex = reactive({
    id: undefined,
    index: undefined
})
//  数据删除
function deleteData() {
    axios.post(path + "post", {
        key: "destroy",
        data: {
            key: ["id"],
            value: [deleIndex.id],
        }
    }).then(date => {
        data.data.splice(deleIndex.index, 1)
        alert("删除成功")
        console.log(date.data.message)
        showDialog.value = false
    })
}
// 列 删除
function handleDelete(index, row) {
    showDialog.value = true
    deleIndex.id = JSON.stringify(row.id)
    deleIndex.index = index
}

function formatDate(date) {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
}
let showDialogConetent = ref(false)
let changeIndex = reactive({
    index: undefined,
    username: undefined,
    password: undefined,
    agePassword: undefined,
    email: undefined,
    nickname: undefined,
    gender: undefined,
    avatar: undefined,
    bio: undefined,
    updated_at: formatDate(new Date())
})
//列 修改内容
function handleChangeConetent(index, row) {
    showDialogConetent.value = true
    changeIndex.index = row.id
    changeIndex.username = row.username
    changeIndex.email = row.email
    changeIndex.nickname = row.nickname
    changeIndex.gender = row.gender
    changeIndex.bio = row.bio
}
//修改内容
async function changeData() {
    if (changeIndex.agePassword == changeIndex.password) {
        uploadImage()
    await axios.post(path + "post", {
        key: "update",
        data: {
            key: ["username", "password", "email", "nickname", "bio", "updated_at", "gender"],
            value: [changeIndex.username, changeIndex.password, changeIndex.email, changeIndex.nickname, changeIndex.bio, changeIndex.updated_at, changeIndex.gender],
        },
        where: {
            key: ["id"],
            value: [changeIndex.index]
        }
    }).then(date => {
        alert("修改成功")
        location.reload()
        showDialog.value = false
        return true
    })
}else {
        tips.value = [tip[1]]
        return false
    }
}

setInterval(() => {
    console.log(changeIndex.gender)
}, 1000);
// 初始化列表
onMounted(() => {
    SearchUser()
})
</script>
<template>
    <el-row :gutter="30">
        <!-- 搜索功能标题 -->
        <el-divider content-position="left">
            <el-text size="large">
                <el-icon>
                    <Search />
                </el-icon> 综合搜索
            </el-text>
        </el-divider>
        <!-- 搜索框 -->
        <el-col v-show="!disabledSearch" :span="8">
            <el-input v-model="input_txt" placeholder="请输入搜索内容" clearable :disabled="disabledSearch" />
        </el-col>
        <!-- 性别选择框 -->
        <el-col v-show="disabledSearch" :span="4">
            <el-select v-model="input_txt" placeholder="Select">
                <el-option v-for="(item, index) in gender.sex" :key="index" :label="gender.tips[index]" :value="item" />
            </el-select>
        </el-col>
        <!-- 搜索范围选择框 -->
        <el-col  :span="4">
            <el-select v-model="SelectValue" placeholder="Select">
                <el-option v-for="(item, index) in userSelect.user" :key="index" :label="userSelect.tips[index]"
                    :value="item" />
            </el-select>
        </el-col>
        <!-- 搜索按钮 -->
        <el-col :span="2">
            <el-button @click="SearchUser()">确认搜索
            </el-button>
        </el-col>
        <!-- 模糊搜索按钮 -->
        <el-col style="text-align: right;" :span="4">
            <el-switch v-model="bool" active-text="模糊搜索"  />
        </el-col>
        <!-- 数据设置标题 -->
        <el-divider content-position="left">
            <el-text size="large">
                <el-icon>
                    <Tools />
                </el-icon>
                设置数据
            </el-text>
        </el-divider>
        <!-- 添加数据按钮 -->
        <el-col :span="24">
            <el-button @click="openData()">添加数据</el-button>
        </el-col>
        <!-- 数据列表标题 -->
        <el-divider content-position="left">
            <el-text size="large">
                <el-icon>
                    <List />
                </el-icon>
                数据列表
            </el-text>
        </el-divider>
        <!-- 数据展示列表 -->
        <el-col :span="24">
            <el-table table-layout="auto" border :data="data.data">
                <el-table-column v-for="(item, index) in prop.fields" :prop="item" :label="prop.tips[index]"
                   header-align="center">
                </el-table-column>
                <el-table-column header-align="center" label="操作">
                    <template #default="scope">
                        <div class="center">
                            <el-button  type="primary" @click="handleChangeConetent(scope.$index, scope.row)"> 修改
                            </el-button>
                            <el-button type="danger" @click="handleDelete(scope.$index, scope.row)"> 删除 </el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </el-col>
        <!-- 确认删除 -->
        <el-dialog v-model="showDialog" title="确认删除" width="30%">
            <div slot="footer">
                <el-button @click="showDialog = false">取消</el-button>
                <el-button type="primary" @click="deleteData()">确定</el-button>
            </div>
        </el-dialog>
        <!-- 修改内容 -->
        <el-dialog v-model="showDialogConetent" title="修改内容" width="30%">
            <div slot="footer">
                <el-form-item label="账号：">
                <el-input clearable v-model="changeIndex.username" placeholder="账号输入" @blur="checkpoint" />
            </el-form-item>
            <el-form-item label="密码：">
                <el-input v-model="changeIndex.password" type="password" show-password placeholder="密码输入" />
            </el-form-item>
            <el-form-item label="确认密码：">
                <el-input v-model="changeIndex.agePassword" type="password" show-password placeholder="密码输入" />
            </el-form-item>
            <el-form-item label="昵称：">
                <el-input v-model="changeIndex.nickname" placeholder="昵称输入" />
            </el-form-item>
            <el-form-item label="邮箱：">
                <el-input v-model="changeIndex.email" placeholder="邮箱输入" />
            </el-form-item>
            <el-form-item label="性别：">
                <el-select v-model="changeIndex.gender" placeholder="Select">
                    <el-option v-for="(item, index) in gender.sex" :key="index" :label="gender.tips[index]" :value="item" />
                </el-select>
            </el-form-item>
            <el-form-item label="头像：">
                <input ref="fileInputRef" type="file" @change="handleFileChange($event)">
                <el-image v-if="imageUrl" :src="imageUrl" @click="openFileInput()"> </el-image>
                <div v-else @click="openFileInput()">
                    <el-icon :size="30">
                        <Plus />
                    </el-icon>
                </div>
            </el-form-item>
            <el-form-item label="简介：">
                <el-input v-model="changeIndex.bio" :rows="2" type="textarea" show-word-limit maxlength="50"
                    placeholder="简介输入" />
            </el-form-item>
            <el-alert v-for="item in tips" :title="item.title" :type="item.type" :description="item.description" show-icon
                :closable="false" />
                <el-button @click="showDialogConetent = false">取消</el-button>
                <el-button type="primary" @click="changeData()">确定</el-button>
            </div>
        </el-dialog>
        <!-- 分页按钮 -->
        <el-col :span="24">
            <el-pagination background layout="prev, pager, next" :page-size="limit" :total="pageCount"
                @current-change="handlePageChange" />
        </el-col>
    </el-row>
    <!-- 添加数据子页面 -->
    <el-dialog v-model="dialogVisible" title="添加数据" width="30%">
        <el-form label-position="left">
            <el-form-item label="账号：">
                <el-input clearable v-model="addUser.username" placeholder="账号输入" @blur="checkpoint" />
            </el-form-item>
            <el-form-item label="密码：">
                <el-input v-model="addUser.password" type="password" show-password placeholder="密码输入" />
            </el-form-item>
            <el-form-item label="确认密码：">
                <el-input v-model="addUser.agePassword" type="password" show-password placeholder="密码输入" />
            </el-form-item>
            <el-form-item label="昵称：">
                <el-input v-model="addUser.nickname" placeholder="昵称输入" />
            </el-form-item>
            <el-form-item label="邮箱：">
                <el-input v-model="addUser.email" placeholder="邮箱输入" />
            </el-form-item>
            <el-form-item label="性别：">
                <el-select v-model="addUser.gender" placeholder="Select">
                    <el-option v-for="(item, index) in gender.sex" :key="index" :label="gender.tips[index]" :value="item" />
                </el-select>
            </el-form-item>
            <el-form-item label="头像：">
                <input ref="fileInputRef" type="file" @change="handleFileChange($event)">
                <el-image v-if="imageUrl" :src="imageUrl" @click="openFileInput()"> </el-image>
                <div v-else @click="openFileInput()">
                    <el-icon :size="30">
                        <Plus />
                    </el-icon>
                </div>
            </el-form-item>
            <el-form-item label="简介：">
                <el-input v-model="addUser.bio" :rows="2" type="textarea" show-word-limit maxlength="50"
                    placeholder="简介输入" />
            </el-form-item>
            <el-alert v-for="item in tips" :title="item.title" :type="item.type" :description="item.description" show-icon
                :closable="false" />
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="clearData()">取消</el-button>
                <el-button type="primary" @click="addData()">
                    确认添加
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>
<style scoped>
.right {
    text-align: right;
}

.el-col {
    margin: 15px 0px 15px 0px;
}

.el-col .el-link {
    margin-left: 5px;
}

.el-row {
    padding: 15px;
    border-radius: 0px 0px 5px 5px;
}

.el-table {
    border-radius: 5px;
    border: 1px solid #dedfe0;
}

.center {
    text-align: center;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}


.el-form-item .el-image {
    border-radius: 100%;
    background-color: rgb(233, 233, 233);
    width: 100px;
    height: 100px;
}

.el-form-item input[type="file"] {
    display: none;
}
</style>